package savelog;

import java.util.ArrayList;
import java.util.Collections;

import com.project.savelog.GameListFragment.GameListListener;
import android.app.Activity;
import android.widget.Button;
import android.widget.PopupWindow;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.os.Bundle;
import android.support.v4.widget.SlidingPaneLayout.LayoutParams;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.View;
import android.view.LayoutInflater;

import android.widget.FrameLayout;

/**
 * Title: GameListActivity class for CSIS 343 Final Project 
 * Description: CS 343 Final Project - GameListActivity This class will handle displaying 
 * the list of games and the information about a game
 * 
 * @author Erik Olson
 * @email erik.olson-5@my.uwrf.edu
 * @author Mike Harmon
 * @email michael.harmon@my.uwrf.edu
 * @author Jack Friermuth
 * @email jack.friermuth@my.uwrf.edu
 * @author Luke Vang
 * @email luke.vang@my.uwrf.edu
 * @author Casey Golla
 * @email casey.golla@my.uwrf.edu
 * @date December 4th 2012
 */
public class GameListActivity extends Activity implements GameListListener{
	
	public static ArrayList<Games> gameListAZ;
	public static ArrayList<Games> gameListLatest;
	public static Games selectedGame;
	public static ArrayList<Saves> selectedSaves;
	public static String deviceName;
	public boolean mDualPane;
	public static String pathToBackup;
	
	public static int currGameSelected;
	private boolean gbaActive, snesActive, segaActive, n64Active, nesActive;
	
	public FrameLayout gameInfoFrame;
	public FragmentManager fragMan;
	
	GameListFragment gListFrag;
	
	/**
	 * method to set up the GameListActivity view structure
	 * @Override
	 */
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.gameinfo_layout);
				
		getPathToBackupAndSystems();
		
		//Seeing if our current layout has the FrameLayout for GameInfoFragment
		gameInfoFrame = (FrameLayout) findViewById(R.id.gameInfoFragment);
		
		//If gameInfoFrame isn't null, then we are in the horizontal GameListActivity layout
		if(gameInfoFrame != null){
			
			mDualPane = gameInfoFrame.getVisibility() == View.VISIBLE;
		
			gameInfoFrame.setVisibility(View.INVISIBLE);
		}
		
		fragMan = getFragmentManager();
		
		//setting list to display all games by default
		selectGameListSystem("All", true);
		
		if (savedInstanceState != null){
			gListFrag = (GameListFragment) fragMan.findFragmentByTag( "gListFrag" );
			gListFrag.setGameListData( gameListAZ, false );
			
		} else {
			gListFrag = new GameListFragment();			
			gListFrag.setGameListData( gameListAZ, false );
			
			fragMan.beginTransaction().replace( R.id.gameListFragment, gListFrag, "gListFrag" ).commit();
		}
	}
	
	public static class GameInfoActivity extends Activity {
		/**
		 * Uses savedInstanceState to create the activity
		 * @Override
		 */
        protected void onCreate(Bundle savedInstanceState) {
			super.onCreate(savedInstanceState);
			
			//getting smallest with in dp
			float smallestWidthDP = getSmallestWidthDP();
			
			if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE && smallestWidthDP > 400) {
                // If the screen is now in landscape mode and we are on a Tablet, then we can close this activity and reload
				//GameListActivity with the dual-pane layout
                finish();
                return;
            }
			
			//getting selected games id
			int selectedGameID = GameListActivity.currGameSelected;
			
			//getting the selected game
			Games selectedGame = GameListActivity.selectedGame;
			
			//getting all saves for the selected game
			ArrayList<Saves> selectedSaves = GameListActivity.selectedSaves;
			
			//loading saves into view
			FragmentManager fragMan = getFragmentManager();
			GameInfoFragment gInfoFrag = new GameInfoFragment();
			gInfoFrag.setGameInfoData(selectedGame, selectedSaves, pathToBackup);
			fragMan.beginTransaction().add(android.R.id.content, gInfoFrag, "gInfoFrag" ).commit();
		}
		
        /**
         * Method to get the smallest width in dp
         * @return smallestWidthDP
         */
		public float getSmallestWidthDP(){
			//getting values
			DisplayMetrics metrics = new DisplayMetrics();
			getWindowManager().getDefaultDisplay().getMetrics(metrics);
			int widthPixels = metrics.widthPixels;
			int heightPixels = metrics.heightPixels;
			int smallestWidthPX = Math.min(widthPixels, heightPixels);
			
			float scaleFactor = metrics.density;
			float smallestWidthDP = smallestWidthPX / scaleFactor;
			
			return smallestWidthDP;
		}
		
		/**
		 * method to get the path to the backup folder from shared preferences 
		 */
		public void getPathToBackup(){
			String backupPath = "";
			
			//getting prefs
			SharedPreferences prefs = this.getSharedPreferences(MainActivity.ACCOUNT_PREFS_NAME, Context.MODE_PRIVATE);
			
			//getting backup path
			backupPath = prefs.getString("m_chosenPathDir", "");
			pathToBackup = backupPath;			
		}
	}

	/**
	 * Method to handle when a game is selected
	 * @param int selectedGameID : the id of the selected game
	 * @Override
	 */
	public void onGameSelected(int selectedGameID) {
		currGameSelected = selectedGameID;
		//checking if portrait or landscape
		if (mDualPane){
			//setting our fragments and game data
			FragmentManager fragMan = getFragmentManager();
			GameInfoFragment gInfoFrag = (GameInfoFragment) fragMan.findFragmentByTag("gInfoFrag");
			selectedGame = MainActivity.data.getGameById(selectedGameID);
			selectedSaves = (ArrayList<Saves>) MainActivity.data.getSavesByGameID(selectedGameID);
			
			//checking if game info fragment is blank
			if(gInfoFrag == null || gInfoFrag.getCurrentGameID() != selectedGameID){
				gameInfoFrame.setVisibility(View.VISIBLE);
				gInfoFrag = new GameInfoFragment();
				
				gInfoFrag.setGameInfoData( selectedGame, selectedSaves, pathToBackup );
				
				FragmentTransaction fragTran = fragMan.beginTransaction();
				fragTran.replace( R.id.gameInfoFragment, gInfoFrag, "gInfoFrag" );
				fragTran.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
				fragTran.commit();
			} 
			
		} else {
			//getting the selected game and the saves for it
			selectedGame = MainActivity.data.getGameById(selectedGameID);
			selectedSaves = (ArrayList<Saves>) MainActivity.data.getSavesByGameID(selectedGameID);
		
			//setting the intent to the GameInfoActivity
			Intent intent = new Intent();
			intent.setClass(this, GameInfoActivity.class);
			startActivity(intent);
		}
		
	}
	
	/**
	 * Creates the PopupWindow for choosing which console
	 * @return null
	 */
	protected void createSystemPopup() {
		//This is to prevent multiple popups on the screen at the same time
		//popupOnScreen = true;
		
		// Inflating the PopupView onto the WebView
		final LayoutInflater layoutInflater = (LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		final View popupView = layoutInflater.inflate( R.layout.system_select_layout, null, false );

		// Creating a new PopupWindow to put in the popupView and setting it's
		// parameters, the first WRAP_CONTENT is for the width
		final PopupWindow popupWindow = new PopupWindow(popupView, LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);

		// In order to have the Popup dismiss on an outside click, you have to
		// set the backgroundDrawable programmatically and not through the layout .xml
		popupWindow.setFocusable(false);
		popupWindow.setTouchable(true);
		popupWindow.setOutsideTouchable(true);
		popupWindow.setBackgroundDrawable(this.getResources().getDrawable(R.drawable.gamesave_table_box));

		// Finding the console button and setting the onClickListener
		Button buttonAll = (Button) popupView.findViewById(R.id.buttonAll);
		final String stringAll = (String) buttonAll.getText();
		buttonAll.setOnClickListener(new Button.OnClickListener() {
			@Override
			public void onClick(View v) {
					selectGameListSystem( stringAll, false );
					popupWindow.dismiss();
				
			}
		});

		// Finding the console button and setting the onClickListener
		Button buttonGBA = (Button) popupView.findViewById(R.id.buttonGBA);
		final String stringGBA = (String) buttonGBA.getText();
		buttonGBA.setOnClickListener(new Button.OnClickListener() {
			@Override
			public void onClick(View v) {
					selectGameListSystem( stringGBA, false );
					popupWindow.dismiss();
				
			}
		});
		if(gbaActive == false){
			buttonGBA.setVisibility(View.GONE);
		}

		// Finding the console button and setting the onClickListener
		Button buttonSNES = (Button) popupView.findViewById(R.id.buttonSNES);
		final String stringSNES = (String) buttonSNES.getText();
		buttonSNES.setOnClickListener(new Button.OnClickListener() {
			@Override
			public void onClick(View v) {
					selectGameListSystem( stringSNES, false );
					popupWindow.dismiss();
				
			}
		});
		if(snesActive == false){
			buttonSNES.setVisibility(View.GONE);
		}

		// Finding the console button and setting the onClickListener
		Button buttonSEGA = (Button) popupView.findViewById(R.id.buttonSEGA);
		final String stringSEGA = (String) buttonSEGA.getText();
		buttonSEGA.setOnClickListener(new Button.OnClickListener() {
			@Override
			public void onClick(View v) {
					selectGameListSystem( stringSEGA, false );
					popupWindow.dismiss();
				
			}
		});
		if(segaActive == false){
			buttonSEGA.setVisibility(View.GONE);
		}

		// Finding the console button and setting the onClickListener
		Button buttonN64 = (Button) popupView.findViewById(R.id.buttonN64);
		final String stringN64 = (String) buttonN64.getText();
		buttonN64.setOnClickListener(new Button.OnClickListener() {
			@Override
			public void onClick(View v) {
					selectGameListSystem( stringN64, false );
					popupWindow.dismiss();
				
			}
		});
		if(n64Active == false){
			buttonN64.setVisibility(View.GONE);
		}

		// Finding the console button and setting the onClickListener
		Button buttonNES = (Button) popupView.findViewById(R.id.buttonNES);
		final String stringNES = (String) buttonNES.getText();
		buttonNES.setOnClickListener(new Button.OnClickListener() {
			@Override
			public void onClick(View v) {
					selectGameListSystem( stringNES, false );
					popupWindow.dismiss();
				
			}
		});
		if(nesActive == false){
			buttonNES.setVisibility(View.GONE);
		}

		// Posting the Popup in a separate runnable so it waits for all other processes to finish before appearing
		popupView.post(new Runnable() {
			public void run() {
				popupWindow.showAtLocation(popupView, Gravity.CENTER, 0, 0);
			}
		});

	}
	
	/**
	 * Method to update the game list fragment
	 * @param updateGameList
	 */
	public void updateGameListFragment(ArrayList<Games> updateGameList){
		gListFrag = new GameListFragment();			
		gListFrag.setGameListData( updateGameList, false );
		
		fragMan.beginTransaction().replace( R.id.gameListFragment, gListFrag, "gListFrag" ).commit();
	}

	/**
	 * Method to get all of the games or by a particular system
	 * @param String system      :     system requested
	 * @param boolean isOnCreate :     if we are calling from the onCreate function
	 */
	public void selectGameListSystem(String system, boolean isOnCreate){
		gameListAZ = new ArrayList<Games>();
		gameListLatest = new ArrayList<Games>();
		
		//checking which system is selected
		if(system == "GBA"){
			gameListAZ = (ArrayList<Games>) MainActivity.data.getGamesOnSystemAZ(5);
			gameListLatest = (ArrayList<Games>) MainActivity.data.getGamesOnSystem(5);
		}
		else if(system == "SNES"){
			gameListAZ = (ArrayList<Games>) MainActivity.data.getGamesOnSystemAZ(1);
			gameListLatest = (ArrayList<Games>) MainActivity.data.getGamesOnSystem(1);
		}
		else if(system == "SEGA"){
			gameListAZ = (ArrayList<Games>) MainActivity.data.getGamesOnSystemAZ(4);
			gameListLatest = (ArrayList<Games>) MainActivity.data.getGamesOnSystem(4);
		}
		else if(system == "N64"){
			gameListAZ = (ArrayList<Games>) MainActivity.data.getGamesOnSystemAZ(2);
			gameListLatest = (ArrayList<Games>) MainActivity.data.getGamesOnSystem(2);
		}
		else if(system == "Nintendo"){
			gameListAZ = (ArrayList<Games>) MainActivity.data.getGamesOnSystemAZ(6);
			gameListLatest = (ArrayList<Games>) MainActivity.data.getGamesOnSystem(6);
		}
		else{
			gameListAZ = (ArrayList<Games>) MainActivity.data.getGamesSortedByGameTitle();
			gameListLatest = (ArrayList<Games>) MainActivity.data.getAllGames();
		}
		Collections.reverse(gameListLatest);
		
		//If we are selecting the system from the PopupWindow (and not from OnCreate),
		if( isOnCreate == false ){
		// then update the GameListFragment with the AZ sorted list of Games
			updateGameListFragment(gameListAZ);
		}
	}

	/**
	 * handle the popup window when the system button is clicked
	 * @Override
	 */
	public void onSystemSelected() {
		createSystemPopup();
	}

	/**
	 * Method to handle when the sort AZ button is clicked 
	 * @Override
	 */
	public void onSortAZ() {
		updateGameListFragment(gameListAZ);		
	}

	/**
	 * Method to handle when the sort latest button is clicked
	 * @Override
     */	
	public void onSortLatest() {
		updateGameListFragment(gameListLatest);		
	}
	
	/**
     * Method to handle getting values from shared preferences
     */
	public void getPathToBackupAndSystems(){
		String backupPath = "";
		
		//getting prefs
		SharedPreferences prefs = this.getSharedPreferences(MainActivity.ACCOUNT_PREFS_NAME, Context.MODE_PRIVATE);
		
		//getting backup path
		backupPath = prefs.getString("m_chosenPathDir", "") + "/backup";
		pathToBackup = backupPath;
		
		//getting which systems are active
		gbaActive = prefs.getBoolean("GBA_CHK", false); 
		snesActive = prefs.getBoolean("SNES_CHK", false); 
		segaActive = prefs.getBoolean("SEGA_CHK", false); 
		n64Active = prefs.getBoolean("N64_CHK", false); 
		nesActive = prefs.getBoolean("NINTENDO_CHK", false);
		
		//getting the device name
		deviceName = prefs.getString("deviceName", "");
	}
}
